﻿
using System.Globalization;

namespace NoNameGoServer.Client.Commands {
    public class PasswordCommand : Command {
        private readonly string _password;
        private bool _passwordSent;

        public PasswordCommand(string password) {
            _password = password;
            _passwordSent = false;
        }

        public override void Execute(NNGSClient nngsClient) {
            // Do nothing, wait for the prompt.
        }

        public override void ProcessReceivedLine(NNGSClient nngsClient, string line, out bool processed) {
			if (line.StartsWith("This is a guest account")) {
				processed = true;
				throw new NNGSClientException("Invalid username.");
			}

			if (_passwordSent == false) {
                bool lineStartsWithLogin = line.StartsWith("Password:", true, CultureInfo.InvariantCulture) ||
                                           line.StartsWith("1 1", true, CultureInfo.InvariantCulture);
                bool bufferStartsWithLogin = false;
                if (!lineStartsWithLogin) {
                    bufferStartsWithLogin =
                        line.StartsWith("Password:", true, CultureInfo.InvariantCulture) ||
                        line.StartsWith("1 1", true, CultureInfo.InvariantCulture);
                }
                if (lineStartsWithLogin || bufferStartsWithLogin) {
                    nngsClient.SendAsync(this, string.Format("{0}\n", _password), null);
                    _passwordSent = true;
                    processed = true;
                    return;
                }
            }

            if (_passwordSent) {
                if (IsPromptLine(line)) {
                    FireCompleted(this, new CompletedArgs());
                    processed = true;
                    return;
                }
				
				if (line.StartsWith("5 Invalid password.")) {
					processed = true;
					throw new NNGSClientException("Incorrect password");
				}
			}

            processed = false;
        }
    }
}
